<!--
 * @Author: whq
 * @Date: 2024-03-13 09:07:45
 * @LastEditTime: 2024-06-13 20:51:26
 * @LastEditors: whq
 * @Description: 
 * @FilePath: /vue3-vant-temp/src/view/ClassIfication/index.vue
-->
<template>
  <van-popup
    :show="activeTopIconShow"
    position="top"
    round
    @close="onPopupClose"
    class="my-van-popup"
  >
    <div v-if="activeTopIconShow">
      <div class="my-van-popup-top">
        <div class="my-van-popup-top-text">
          <!-- {{ tableSelect.find((f) => f.id === activeTabId)?.text }} -->
          {{ leftState?.[activeData?.index]?.text }}
        </div>
        <van-icon name="arrow-up" @click="activeTopIconShow = false" />
      </div>
      <div class="my-van-popup-item-com">
        <div
          class="my-van-popup-item"
          :class="{ active: activeTabId === item.id }"
          v-for="item in tableSelect"
          :key="item.index"
          :id="`tab-item-top-${item.id}`"
          @click="scrollToAnchor(item.id)"
        >
          {{ item?.text }}
        </div>
      </div>
    </div>
  </van-popup>

  <van-tree-select
    :items="leftState"
    :main-active-index.sync="activeData.index"
    :height="props.height"
    @click-nav="onNavClick"
    class="my-van-tree-select"
    ref="treeSelectRef"
  >
    <template #content>
      <div class="tab-item-top" ref="tabItemTop">
        <div class="tab-item-top-scroll">
          <div
            class="tab-item-top-item"
            :class="{ active: activeTabId === item.id }"
            v-for="item in tableSelect"
            :key="item.index"
            :id="`tab-item-top-${item.id}`"
            @click="scrollToAnchor(item.id)"
          >
            {{ item?.text }}
          </div>
        </div>
        <div
          v-if="tableSelect?.length"
          class="tab-item-top-icon"
          @click="activeTopIconShow = true"
        >
          <van-icon name="arrow-down" />
        </div>
      </div>
      <div class="tab-item-content" v-if="tableSelect" ref="tabItemContentRef">
        <div
          class="tab-item-content-item"
          v-for="item in tableSelect"
          :key="item.index"
          :id="`content-item-${item.id}`"
        >
          <div class="tab-item-content-title">
            {{ item?.text }}
          </div>
          <div class="tab-item-content-childrens">
            <div
              v-if="item.children"
              class="tab-item-content-childrens-item"
              v-for="childrenItem in item.children"
              :key="childrenItem.id"
              @click="onClickItem(item, childrenItem)"
            >
              <van-image
                width="70"
                height="70"
                src="https://img.yzcdn.cn/vant/cat.jpeg"
              />
              <div>{{ childrenItem.text }}</div>
            </div>
          </div>
        </div>
      </div>

      <van-empty v-else description="暂无数据" />
    </template>
  </van-tree-select>
</template>

<script setup>
import {
  onMounted,
  ref,
  onUnmounted,
  defineEmits,
  watch,
  nextTick,
} from "vue";
import globals from "@/store/globals";
import { publicApi } from "@apis/index";
import { showFailToast } from "vant";
// https://vant-ui.github.io/vant-weapp/#/tree-select

// 左侧菜单数据
const leftd = [
  {
    id: "11",
    text: "数码",
  },
  {
    id: "22",
    text: "湿巾",
  },
  {
    id: "33",
    text: "个人清洁",
  },
  {
    id: "44",
    text: "美妆护肤",
  },
  {
    id: "55",
    text: "母婴用品",
  },
  {
    id: "66",
    text: "食品饮料",
  },
  {
    id: "77",
    text: "生鲜水果",
  },
  {
    id: "88",
    text: "酒水茶饮",
  },
  {
    id: "99",
    text: "家居家纺",
  },
  {
    id: "100",
    text: "家用电器",
  },
  {
    id: "111",
    text: "电脑办公",
  },
  {
    id: "122",
    text: "手机数码",
  },
  {
    id: "133",
    text: "家居家纺",
  },
  {
    id: "144",
    text: "家用电器",
  },
  {
    id: "155",
    text: "电脑办公",
  },
  {
    id: "166",
    text: "手机数码",
  },
  {
    id: "177",
    text: "家居家纺",
  },
  {
    id: "188",
    text: "家用电器",
  },
  {
    id: "199",
    text: "电脑办公",
  },
  {
    id: "200",
    text: "手机数码",
  },
  {
    id: "211",
    text: "家居家纺",
  },
  {
    id: "222",
    text: "家用电器",
  },
  {
    id: "233",
    text: "电脑办公",
  },
  {
    id: "244",
    text: "手机数码",
  },
  {
    id: "255",
    text: "家居家纺",
  },
];

// 右侧 模拟数据
const rightd = [
  {
    id: "11",
    text: "数码",
    children: [
      {
        id: "111",
        text: "手机",
        children: [
          {
            id: "1111",
            text: "手机1",
            tableLogo: "https://img.yzcdn.cn/vant/apple-1.jpg",
            price: "1000",
            tableName: "手机1",
          },
          {
            id: "1112",
            text: "手机2",
            tableLogo: "https://img.yzcdn.cn/vant/apple-1.jpg",
            price: "1000",
            tableName: "手机2",
          },
          {
            id: "1113",
            text: "手机3",
            tableLogo: "https://img.yzcdn.cn/vant/apple-1.jpg",
            price: "1000",
            tableName: "手机3",
          },
          {
            id: "1114",
            text: "手机4",
            tableLogo: "https://img.yzcdn.cn/vant/apple-1.jpg",
            price: "1000",
            tableName: "手机4",
          },
          {
            id: "1115",
            text: "手机5",
            tableLogo: "https://img.yzcdn.cn/vant/apple-1.jpg",
            price: "1000",
            tableName: "手机5",
          },
          {
            id: "1116",
            text: "手机6",
            tableLogo: "https://img.yzcdn.cn/vant/apple-1.jpg",
            price: "1000",
            tableName: "手机6",
          },
          {
            id: "1117",
            text: "手机7",
            tableLogo: "https://img.yzcdn.cn/vant/apple-1.jpg",
            price: "1000",
            tableName: "手机7",
          },
          {
            id: "1118",
            text: "手机8",
            tableLogo: "https://img.yzcdn.cn/vant/apple-1.jpg",
            price: "1000",
            tableName: "手机8",
          },
          {
            id: "1119",
            text: "手机9",
            tableLogo: "https://img.yzcdn.cn/vant/apple-1.jpg",
            price: "1000",
            tableName: "手机9",
          },
          {
            id: "11110",
            text: "手机10",
            tableLogo: "https://img.yzcdn.cn/vant/apple-1.jpg",
            price: "1000",
            tableName: "手机10",
          },
        ],
      },
      {
        id: "112",
        text: "电脑",
        children: [
          {
            id: "1121",
            text: "华为笔记本",
            tableLogo: "https://img.yzcdn.cn/vant/apple-1.jpg",
            price: "12043",
            tableName: "华为笔记本",
          },
          {
            id: "1122",
            text: "华硕笔记本",
            tableLogo: "https://img.yzcdn.cn/vant/apple-1.jpg",
            price: "12345",
            tableName: "华硕笔记本",
          },
          {
            id: "1123",
            text: "联想笔记本",
            tableLogo: "https://img.yzcdn.cn/vant/apple-1.jpg",
            price: "7867",
            tableName: "联想笔记本",
          },
          {
            id: "1124",
            text: "玩家",
            tableLogo: "https://img.yzcdn.cn/vant/apple-1.jpg",
            price: "7867",
            tableName: "联想玩家笔记本",
          },
          {
            id: "1125",
            text: "百家之言",
            tableLogo: "https://img.yzcdn.cn/vant/apple-1.jpg",
            price: "7867",
            tableName: "百家之言",
          },
        ],
      },
      {
        id: "113",
        text: "手机配件",
        children: [
          {
            id: "1131",
            text: "手机配件1",
            tableLogo: "https://img.yzcdn.cn/vant/apple-1.jpg",
            price: "1000",
            tableName: "手机配件1",
          },
          {
            id: "1132",
            text: "手机配件2",
            tableLogo: "https://img.yzcdn.cn/vant/apple-1.jpg",
            price: "1000",
            tableName: "手机配件2",
          },
          {
            id: "1133",
            text: "手机配件3",
            tableLogo: "https://img.yzcdn.cn/vant/apple-1.jpg",
            price: "1000",
            tableName: "手机配件3",
          },
          {
            id: "1134",
            text: "手机配件4",
            tableLogo: "https://img.yzcdn.cn/vant/apple-1.jpg",
            price: "1000",
            tableName: "手机配件4",
          },
          {
            id: "1135",
            text: "手机配件5",
            tableLogo: "https://img.yzcdn.cn/vant/apple-1.jpg",
            price: "1000",
            tableName: "手机配件5",
          },
          {
            id: "1136",
            text: "手机配件6",
            tableLogo: "https://img.yzcdn.cn/vant/apple-1.jpg",
            price: "1000",
            tableName: "手机配件6",
          },
          {
            id: "1137",
            text: "手机配件7",
            tableLogo: "https://img.yzcdn.cn/vant/apple-1.jpg",
            price: "1000",
            tableName: "手机配件7",
          },
        ],
      },
      {
        id: "114",
        text: "电脑配件",
        children: [
          {
            id: "1141",
            text: "电脑配件1",
            tableLogo: "https://img.yzcdn.cn/vant/apple-1.jpg",
            price: "1000",
            tableName: "电脑配件1",
          },
          {
            id: "1142",
            text: "电脑配件2",
            tableLogo: "https://img.yzcdn.cn/vant/apple-1.jpg",
            price: "1000",
            tableName: "电脑配件2",
          },
          {
            id: "1143",
            text: "电脑配件3",
            tableLogo: "https://img.yzcdn.cn/vant/apple-1.jpg",
            price: "1000",
            tableName: "电脑配件3",
          },
        ],
      },
      {
        id: "115",
        text: "主机电脑配件",
        children: [
          {
            id: "1151",
            text: "主机电脑配件1",
            tableLogo: "https://img.yzcdn.cn/vant/apple-1.jpg",
            price: "1000",
            tableName: "主机电脑配件1",
          },
          {
            id: "1152",
            text: "主机电脑配件2",
            tableLogo: "https://img.yzcdn.cn/vant/apple-1.jpg",
            price: "1000",
            tableName: "主机电脑配件2",
          },
          {
            id: "1153",
            text: "主机电脑配件3",
            tableLogo: "https://img.yzcdn.cn/vant/apple-1.jpg",
            price: "1000",
            tableName: "主机电脑配件3",
          },
        ],
      },
    ],
  },
  {
    id: "22",
    text: "生活用品",
    children: [
      {
        id: "221",
        text: "生活用品1",
        children: [
          {
            id: "2211",
            text: "生活用品11",
            tableLogo: "https://img.yzcdn.cn/vant/apple-1.jpg",
            price: "1000",
            tableName: "生活用品11",
          },
          {
            id: "2212",
            text: "生活用品12",
            tableLogo: "https://img.yzcdn.cn/vant/apple-1.jpg",
            price: "1000",
            tableName: "生活用品12",
          },
          {
            id: "2213",
            text: "生活用品13",
            tableLogo: "https://img.yzcdn.cn/vant/apple-1.jpg",
            price: "1000",
            tableName: "生活用品13",
          },
        ],
      },
    ],
  },
  {
    id: "33",
    text: "个人清洁",
    children: [
      {
        id: "331",
        text: "个人清洁1",
        children: [
          {
            id: "3311",
            text: "个人清洁11",
            tableLogo: "https://img.yzcdn.cn/vant/apple-1.jpg",
            price: "1000",
            tableName: "个人清洁11",
          },
          {
            id: "3312",
            text: "个人清洁12",
            tableLogo: "https://img.yzcdn.cn/vant/apple-1.jpg",
            price: "1000",
            tableName: "个人清洁1222",
          },
        ],
      },
      {
        id: "332",
        text: "个人清洁2",
        children: [
          {
            id: "3321",
            text: "个人清洁21",
            tableLogo: "https://img.yzcdn.cn/vant/apple-1.jpg",
            price: "1000",
            tableName: "个人清洁21",
          },
          {
            id: "3322",
            text: "个人清洁22",
            tableLogo: "https://img.yzcdn.cn/vant/apple-1.jpg",
            price: "1000",
            tableName: "个人清洁22",
          },
        ],
      },
    ],
  },
];
// 需要对应 要与实际数据为准

// 定义 refs
const rightState = ref([]);
const leftState = ref([]);

const props = defineProps({
  rightDatas: {
    type: Array,
    default: () => [],
  },
  leftDatas: {
    type: Array,
    default: () => [],
  },
  // 组件的高度
  height: {
    type: String,
    default: "80vh",
  },
});
// 监听 props 变化，实时更新 refs 值
watch(
  () => props.rightDatas,
  (newVal) => {
    rightState.value = newVal?.length ? newVal : rightd;
  },
  {
    deep: true,
    immediate: true,
  }
);

watch(
  () => props.leftDatas,
  (newVal) => {
    leftState.value = newVal?.length ? newVal : leftd;
  },
  {
    deep: true,
    immediate: true,
  }
);

const emits = defineEmits(["on-click-item"]);

const treeSelectRef = ref(null);
const tabItemContentRef = ref(null);

const tableSelect = ref([]); // 当前分类下的数据
const activeData = ref({
  index: 0,
}); // 当前分类下的数据

const tabItemTop = ref(null);
const activeTabId = ref(null); // 当前选中的 tab id
const activeTabItemId = ref(null);

const activeTopIconShow = ref(false);

const getInit = async () => {
  tableSelect.value = rightState?.value?.find(
    (f) => f.id === leftState?.value?.[activeData?.value?.index]?.id
  )?.children;
  activeTabId.value = tableSelect?.value?.[0]?.id || null;
};
const onPopupClose = () => {
  activeTopIconShow.value = false;
};
// 防抖工具函数
const debounce = (func, delay) => {
  let timeoutId;
  return function () {
    const context = this;
    const args = arguments;
    clearTimeout(timeoutId);
    timeoutId = setTimeout(() => func.apply(context, args), delay);
  };
};
const onNavClick = (index) => {
  activeData.value.index = index;
  tableSelect.value = rightState?.value?.find(
    (f) => f?.id === leftState?.value?.[index]?.id
  )?.children;
  activeTabId.value = tableSelect?.value?.[0]?.id || null;

  // 获取点击的导航项元素
  // const navItemElement = treeSelectRef?.value?.$el?.querySelectorAll(".van-tree-select__nav-item");
  // const navItemElement = treeSelectRef?.value
  // console.log(navItemElement, "==navItemElement===");
  // console.log(navItemElement.offsetTop,"==navItemElement.offsetTop==");
  const navItemElement = treeSelectRef.value?.$el.querySelectorAll(
    ".van-tree-select__nav-item"
  )[index];
  console.log(navItemElement, "==navItemElement===");

  if (navItemElement) {
    const scrollContainer = treeSelectRef.value?.$el.querySelector(
      ".van-tree-select__nav"
    );
    const navItemTop = navItemElement.offsetTop;
    const scrollTopPosition = navItemTop - 100; // 100像素距离顶部
    scrollContainer?.scrollTo({ top: scrollTopPosition, behavior: "smooth" });
  }
};

let isClicking = false;
let scrollTimeout = null;

const scrollToAnchor = (id) => {
  if (id === activeTabId.value) return;
  activeTabId.value = id;
  console.log(id, "=scrollToAnchor=id==");

  const anchorElement = document.getElementById(`content-item-${id}`);
  const anchorPElement = document.querySelector(`.tab-item-content`);

  if (anchorElement) {
    isClicking = true;
    const anchorPosition = anchorElement.offsetTop + window.scrollY - 40;

    console.log(anchorPosition, "===anchorPosition===");

    // 清除之前的定时器
    if (scrollTimeout) clearTimeout(scrollTimeout);

    // 设置滚动动画结束后取消点击状态的定时器
    scrollTimeout = setTimeout(() => {
      isClicking = false;
    }, 800);

    anchorPElement.scrollTo({
      top: anchorPosition,
      behavior: "smooth",
    });
  }

  setTimeout(() => {
    const tabElement = document.getElementById(`tab-item-top-${id}`);
    const tabContainer = document.querySelector(".tab-item-top-scroll");
    if (tabElement && tabContainer) {
      const containerWidth = tabContainer.clientWidth;
      const tabWidth = tabElement.clientWidth;
      const tabLeft = tabElement.offsetLeft;
      const scrollLeft = tabLeft - containerWidth / 2 + tabWidth / 2;
      tabContainer.scrollTo({ left: scrollLeft, behavior: "smooth" });

      // 清除之前的定时器
      if (scrollTimeout) clearTimeout(scrollTimeout);

      // 设置滚动动画结束后取消点击状态的定时器
      scrollTimeout = setTimeout(() => {
        isClicking = false;
      }, 800);
    }
  }, 100);
};

const updateActiveAnchor = () => {
  if (isClicking) return;
  const tabTop = tabItemTop.value.offsetTop;
  const contents = document.querySelectorAll(".tab-item-content-item");
  let activeId = "";
  console.log(tabTop, "==tabTop===");
  contents.forEach((content) => {
    const rect = content.getBoundingClientRect();
    if (rect.top <= tabTop && rect.bottom >= tabTop) {
      activeId = content.id.replace("content-item-", "");
    }
  });
  console.log(activeId, "==activeId");
  if (activeId) {
    activeTabId.value = activeId;
    const tabElement = document.getElementById(`tab-item-top-${activeId}`);
    const tabContainer = document.querySelector(".tab-item-top-scroll");
    if (tabElement && tabContainer) {
      const containerWidth = tabContainer.clientWidth;
      const tabWidth = tabElement.clientWidth;
      const tabLeft = tabElement.offsetLeft;
      const scrollLeft = tabLeft - containerWidth / 2 + tabWidth / 2;
      tabContainer.scrollTo({ left: scrollLeft, behavior: "smooth" });

      // 清除之前的定时器
      if (scrollTimeout) clearTimeout(scrollTimeout);

      // 设置滚动动画结束后取消点击状态的定时器
      scrollTimeout = setTimeout(() => {
        isClicking = false;
      }, 800);
    }
  }
};
const onClickItem = (item, childrenItem) => {
  console.log(item, "==on-click-item item===");
  console.log(childrenItem, "==on-click-item childrenItem===");
  emits("on-click-item", item, childrenItem);
};

onMounted(() => {
  getInit();
  tabItemContentRef.value.addEventListener("scroll", debounce(updateActiveAnchor, 300));
});

onUnmounted(() => {});
</script>

<style lang="scss" scoped>
.my-van-tree-select {
  background: #f4f4f4 !important;
}
.my-van-tree-select :deep(.van-tree-select__nav-item) {
  text-align: center !important;
  background: #f4f4f4 !important;
}

.my-van-tree-select :deep(.van-sidebar-item__text) {
  color: #858585;
}

.my-van-tree-select :deep(.van-sidebar-item--select) {
  .van-sidebar-item__text {
    font-weight: bold !important;
    font-size: 16px;
    color: #ef2d23;
  }
}

.my-van-tree-select :deep(.van-sidebar-item--select:before) {
  content: none;
}

// 隐藏滚动条
.my-van-tree-select :deep(.van-tree-select__content) {
  background: #f4f4f4 !important;
  overflow: hidden;
  position: relative;
  &::-webkit-scrollbar {
    display: none !important;
    width: 0 !important;
  }
}
.my-van-tree-select :deep(.van-tree-select__nav) {
  &::-webkit-scrollbar {
    display: none !important;
    width: 0 !important;
  }
}

.tab-item-top {
  display: flex;
  height: 40px;
  align-items: center;
  background: #f4f4f4 !important;
  overflow: hidden;
  //position: absolute;
  position: sticky;
  top: 0;
  z-index: 1000;
  width: 100%;
  .tab-item-top-scroll {
    display: flex;
    overflow-x: auto;
    width: auto;
    white-space: nowrap;
    scrollbar-width: none;
    -ms-overflow-style: none;
    margin-right: 30px;
    .tab-item-top-item {
      padding: 0 12px;
      margin: 0 7px;
      border-radius: 15px / 50%;
      color: #858585;
      background-color: #ffffff;
      display: inline-block;
      text-align: center;
      line-height: 26px;
      height: 28px;
      white-space: nowrap;
      box-sizing: border-box;
      border: 1px solid #f4f4f4;
      font-size: 14px;

      &.active {
        color: #ef2d23;
        background-color: #feeae9;
        border: 1px solid #ef2d23;
        box-sizing: border-box;
      }
    }
  }
  .tab-item-top-icon {
    border-radius: 50%;
    height: 28px;
    width: 26px;
    position: absolute;
    right: 10px;
    /* 添加单边阴影效果（左边） */
    box-shadow: -10px 0 20px 2px rgb(221 221 221 / 20%);
    .van-icon {
      font-size: 14px;
      height: 28px;
      width: 26px;
      display: flex;
      justify-content: center;
      align-items: center;
      border-radius: 50%;
      background: #fff;
    }
  }
  .tab-item-top-scroll::-webkit-scrollbar {
    display: none;
  }
}

.tab-item-content {
  overflow: auto;
  height: calc(100% - 40px);
  &::-webkit-scrollbar {
    display: none !important;
    width: 0 !important;
  }
  .tab-item-content-item {
    background: #ffffff;

    border-radius: 20px;
    padding: 7px 4px;
    //margin: 10px 5px;
    margin: 0 10px 5px 5px;
    .tab-item-content-title {
      font-size: 16px;
      font-weight: bold;
      color: #2f2f2f;
      margin-left: 10px;
    }

    .tab-item-content-childrens {
      display: flex;
      flex-wrap: wrap;

      .tab-item-content-childrens-item {
        display: flex;
        flex-direction: column;
        justify-content: center;
        //flex: 1 1 calc(33.33% - 20px);
        //width: calc(33.33% - 20px);
        width: calc(33.33% - 16px);
        margin: 8px;
        box-sizing: border-box;
        overflow: hidden;
        > div:nth-of-type(2) {
          font-size: 12px;
          color: #858585;
          text-align: center;
        }
      }
    }
  }
}

.my-van-popup {
  padding: 20px;
  .my-van-popup-top {
    margin-bottom: 7px;
    display: flex;
    justify-content: space-between;

    .my-van-popup-top-text {
      font-size: 16px;
      font-weight: bold;
      color: #2f2f2f;
    }
    .van-icon {
      font-size: 16px;
    }
  }

  .my-van-popup-item {
    padding: 0 12px;
    margin: 5px 12px;
    border-radius: 15px / 50%;
    color: #858585;
    background-color: #ffffff;
    display: inline-block;
    text-align: center;
    line-height: 26px;
    height: 26px;
    white-space: nowrap;
    box-sizing: border-box;
    border: 1px solid #ffffff;
    &.active {
      color: #ef2d23;
      font-weight: bold;
      background-color: #feeae9;
      border: 1px solid #ef2d23;
      box-sizing: border-box;
    }
  }
}
</style>
